package controller

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

func BaiduCheck(imgurl string, phone, idNumber, schooid string) (err error) {
	log.Println("开始上传百度人脸库")
	var (
		faceurl      string
		request      *http.Request
		response     *http.Response
		ret_maps     map[string]interface{}
		ret_maplog   map[string]interface{}
		databyte     []byte
		access_token string
	)

	faceurl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=dVK2KtDUCCHU8zdWO4mA0xSf&client_secret=3W1jIetONrtSGjISdTZQrnEtyLkjNZs7"

	if request, err = http.NewRequest("POST", faceurl, nil); err != nil {
		return err
	}

	request.Header.Set("Content-Type", "application/json; charset=UTF-8")
	if response, err = http.DefaultClient.Do(request); err != nil {
		return err
	}

	defer response.Body.Close()
	databyte, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	err = json.Unmarshal(databyte, &ret_maps)
	if err != nil {
		return err
	}
	access_token = ret_maps["access_token"].(string)

	//上传百度人脸库
	var faceaddurl string

	faceaddurl = "https://aip.baidubce.com/rest/2.0/face/v2/faceset/user/add?access_token=" + access_token

	resp, err := http.Get(imgurl)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	datas, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	dataface := make(url.Values)
	dataface["uid"] = []string{idNumber}                                   //学员身份证号   百度用户ID
	dataface["user_info"] = []string{phone}                                //学员信息   百度用户信息
	dataface["group_id"] = []string{schooid}                               //驾校ID 百度人脸分组ID
	dataface["image"] = []string{base64.StdEncoding.EncodeToString(datas)} //图片经过base64编码
	dataface["action_type"] = []string{"replace"}                          //默认空   replace为替换头像
	r, err := http.PostForm(faceaddurl, dataface)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	respdataface, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	err = json.Unmarshal(respdataface, &ret_maplog)
	if err != nil {
		return err
	}
	log.Println(ret_maplog["error_msg"])
	if ret_maplog["error_msg"] != nil {
		return errors.New("上传百度人脸失败！")
	}
	return nil
}
